<template>
    <!-- 下划线 -->
    <el-divider content-position="left">
        <h2>文章管理</h2>
    </el-divider>

    <!-- 表单对话框组件 -->
    <el-button type="primary" @click="dialogFormVisible = true">
        新增
    </el-button>
    <el-dialog v-model="dialogFormVisible" title="编辑文章" width="70%">
        <!-- 填写我们的表单 -->
        <!-- 表单组件 -->
        <el-form :model="form" label-width="120px">
            <el-form-item label="标题">
                <el-input v-model="form.article_title" />
            </el-form-item>
            <el-form-item label="导航分类">
                <el-select v-model="form.nav_name" placeholder="">
                    <!-- 代码片段 -->
                    <el-option v-for="(item, index) in  nav_list.arr" :label="item.nav_name" :value="item.nav_name" />
                </el-select>
            </el-form-item>

            <el-form-item label="文章类型">
                <el-select v-model="form.article_type" placeholder="请选择文章类型">
                    <el-option label="纯文字" value="1" />
                    <el-option label="图文" value="2" />
                    <el-option label="纯图片" value="3" />
                </el-select>
            </el-form-item>

            <el-form-item label="是否推荐">
                <el-switch v-model="form.article_hot2" />
            </el-form-item>

            <el-form-item label="地址">
                <el-input v-model="form.article_address" />
            </el-form-item>

            <el-form-item label="标签">
                <el-checkbox-group v-model="form.article_tags">
                    <el-checkbox label="美食" name="type" />
                    <el-checkbox label="风景" name="type" />
                    <el-checkbox label="爬山" name="type" />
                    <el-checkbox label="钓鱼" name="type" />
                </el-checkbox-group>
            </el-form-item>

            <el-form-item label="纯文字" v-if="form.article_type == 1">
                <el-input v-model="text" type="textarea" />
            </el-form-item>

            <el-form-item label="图片文字" v-if="form.article_type == 2">
                <!-- 富文本框组件 -->
                <myEditor />
            </el-form-item>

            <el-form-item label="纯图片" v-if="form.article_type == 3">
                <el-upload v-model:file-list="fileList" :action="options.add" list-type="picture-card"
                    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="uploadImgFn" name="photo"
                    :data="data" limit="9">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
            </el-form-item>


            <el-form-item label="作者">
                <el-input v-model="form.article_author" />
            </el-form-item>

        </el-form>

        <!-- 对话框的按钮 -->
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="onSubmit">
                    发布
                </el-button>
            </span>
        </template>


    </el-dialog>

    <!-- 表格组件 -->
    <!-- prop: 填写每个对象的属性 -->
    <!-- label: 表格头描述 -->
    <el-table :data="tableData" style="width: 90%" height="400">
        <!-- <el-table-column fixed prop="article_create_time" label="日期" width="150" /> -->
        <el-table-column fixed label="日期" width="150">
            <template #default="scope">
                <span>{{ formatime(scope.row.article_create_time) }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="article_author" label="作者" width="120" />
        <el-table-column prop="article_type" label="类型" width="120" />
        <el-table-column prop="nav_name" label="导航" width="100" />
        <el-table-column prop="article_hot" label="是否推荐" width="120" />
        <el-table-column prop="article_address" label="地址" width="120" />
        <el-table-column prop="article_title" label="标题" width="400" />
        <el-table-column align="right">
            <template #default="scope">
                <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="example-pagination-block" v-if="total!=0">
        <el-pagination 
             layout="prev, pager, next" :total="total" 
             @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
</template>

<script setup lang="ts" name="editor">
import { ref, reactive } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile , Action} from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import myEditor from '../../components/myEditor.vue'
import { listNavFunc } from '../../api/index'
import { useArticleStore } from '../../store/article'
import { addArticleFunc, listArticleFunc, removePhotoFunc,removeArticleFunc } from '../../api/index'
import moment from 'moment'
import { HOST_URL } from '../../config/host'
// 记录处理图片的接口地址
const options = reactive({ add: `${HOST_URL}/photo/preview` })

// 创建文章状态管理对象
let articleStore: any = useArticleStore()
//记录纯文字
let text = ref('')
// 记录所有列表
let total = ref(0)
// 记录文章数组
let tableData = ref([])
// tableData.value = []
// 记录导航列表
let nav_list: any = reactive({ arr: [] })
let data: any = reactive({ token: localStorage.getItem("AUTO_TOKEN") })
let arr: string[] = [];//记录纯图片
// 控制表单对话框
let dialogFormVisible = ref(false)
// 收集表单信息
const form = reactive({
    article_title: '',
    article_author: '',
    article_content: '',
    article_type: 1,// 1: 纯文字  2：图片和文字  3：纯图片
    article_address: '',
    article_tags: [],
    nav_name: '',
    article_hot2: false, // 0: 不推荐   1：推荐
    article_hot: 0,
})
// 单独记录所有图片
const fileList = ref<UploadUserFile[]>([
    // {
    //     name: 'food.jpeg',
    //     url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
    // },
])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

// 弹窗提示
const open = (message:string, cb: any) => {
  ElMessageBox.alert(message, {
    confirmButtonText: '确定',
    callback: (action: Action) => {
        //执行回调函数
        cb && cb()
    },
  })
}

// 删除图片
const handleRemove: UploadProps['onRemove'] = (uploadFile: any, uploadFiles: any) => {
    console.log(uploadFile, uploadFiles)
    let picUrl: string = uploadFile.response.picUrl;
    // console.log('x:',picUrl)
    removePhotoFunc({ picUrl })
        .then(
            content => {
                console.log(content)
            }
            ,
            err => {
                console.log(err)
            }
        )
}
// 预览图片
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
    // console.log('图片：',uploadFile)
}
// 上传图片
const uploadImgFn = (photo: any) => {
    console.log('图片：', photo)
    let { picUrl, code } = photo;
    if (code == 200) {
        // 记录每一张图片
        arr.push(picUrl)
    }
}
// 获取图片和文本
const addHtml = () => {
    // console.log('富文本框的内容：',articleStore.$state.html);
    if (articleStore.$state.html == '') {
        ElMessage.error('输入框不能为空。');
        return;
    }
    // 收集富文本框的内容
    form.article_content = articleStore.$state.html;
}
// 获取纯文本
const addText = () => {
    // console.log(text.value)
    // console.log('-->',form.article_hot)
    if (text.value == '') {
        ElMessage.error('输入框不能为空。');
        return;
    }
    // 获取纯文本（输入域的内容）
    form.article_content = text.value;
}
// 获取纯图片
const addPhoto = () => {
    // console.log('处理纯图片逻辑')
    form.article_content = JSON.stringify(arr);
}
// 发布文章
const onSubmit = async () => {
    form.article_hot = form.article_hot2 == true ? 1 : 0;
    // console.log('submit!')
    if (form.article_type == 1) {
        addText();
    }
    else
        if (form.article_type == 2) {
            addHtml();
        }
        else {
            addPhoto();
        }
    let {
        article_title,
        article_author,
        article_content,
        article_address,
        nav_name
    } = form;

    // 判断表单信息是缺少值
    if (article_title == '' || article_author == '' || article_content == '' || article_address == '' || nav_name == '') {
        ElMessage.error('缺少参数，请检查一遍再提交。');
        return;
    }

    // 调用发布文章的接口
    await addArticleFunc({ ...form })
        .then(
            (content: any) => {
                // console.log('2.0',content);
                if (content.code == 200) {
                    ElMessage.success(content.msg);
                    // 重置编辑框或者表单
                    form.article_title = '';
                    form.article_author = '';
                    form.article_content = '';
                    form.article_address = '';
                    form.article_tags = [];
                    form.nav_name = '';
                    // 重置pinia储存中的数据
                    articleStore.changeHtml('');
                    // 图片数组
                    fileList.value = [];
                    arr = [];
                    // 重新获取文章
                    getArticleListFn();
                }
                else {
                    ElMessage.error(content.msg);
                }
            },
            err => {
                console.log(err);
            }
        )
        .then(
            () => {
                // 隐藏对话框
                dialogFormVisible.value = false
                // text.value = "";
            }
        )
}

// 获取文章列表
const getArticleListFn = (page=1,pageSize=10)=> {
     // 初始化文章列表
    //  console.log({page,pageSize})
     listArticleFunc({page,pageSize}).then(
        (content: any) => {
            // console.log('1.0', content)
            if (content.code == 200) {
                tableData.value = content.result;
                total.value = content.total;
            }
        }
    )
}

// 初始化页面
const initFn = async () => {
    //初始化文章
    getArticleListFn(1,10);
    // 初始化导航列表
    await listNavFunc().then(
        (content: any) => {
            // console.log('2.0',content)
            if (content.code == 200) {
                nav_list.arr = content.result;
            }
        }
    )
}
initFn();

// 删除文件的方法
const handleDelete = (index: number, row: any) => {
  //console.log(index, row)
  //弹窗提示
  open(`删除“${row.article_title.slice(0,6)}...”这篇文章吗?`,
  async ()=>{
    // 文章ID
    let article_id = row.article_id;
    // 删除文章
    await removeArticleFunc({article_id})
    .then(
        (content: any)=>{
            // 提示
           content.code == 200 ?  ElMessage.success(content.msg) :  ElMessage.error(content.msg);
           if(content.code == 200) {
                initFn();
           }
        },
        err=>{
            console.log(err);
        }
    )
  })
}

// 格式化时间
const formatime = (time:string) => {
   return  moment(time).format("YY-MM-DD hh:mm:ss")
}

// 分页数据
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  getArticleListFn(val,10)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  getArticleListFn(val,10)
}

</script>

<style>
.el-textarea__inner {
    height: 200px;
}
</style>
